package cc.chengheng.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class AuthFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 最优先，也就是第一个要执行的过滤器
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 这里转发token
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext currentRequestContext = RequestContext.getCurrentContext(); // 网关把Request的信息封装到上下文中拿来用
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // 从上下文中获取认证
        if (!(authentication instanceof OAuth2Authentication)) {
            return null;
        }

        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) authentication;
        Authentication userAuthentication = oAuth2Authentication.getUserAuthentication();

        // 获取当前用户的身份信息
        String principal = userAuthentication.getName();

        // 获取当前用户的权限信息
        List<String> authorities = new ArrayList<>();
        userAuthentication.getAuthorities().forEach(c -> authorities.add(c.getAuthority()));

        OAuth2Request oAuth2Request = oAuth2Authentication.getOAuth2Request();
        Map<String, String> requestParameters = oAuth2Request.getRequestParameters();
        Map<String, Object> jsonToken = new HashMap<>(requestParameters);

        jsonToken.put("principal", principal);
        jsonToken.put("authorities", authorities);

        // 把身份信息和权限信息放在json中，加入http的header中
        String s = null;
        try {
            // json 编码为base64
            s = new ObjectMapper().writeValueAsString(jsonToken);
            byte[] encode = Base64.getEncoder().encode(s.getBytes(StandardCharsets.UTF_8));
            String s1 = new String(encode, 0, encode.length);

            currentRequestContext.addZuulRequestHeader("json-token", s1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 转发给微服务

        return null;
    }
}
